package com.cn.system.controller;

import com.cn.common.annotation.Log;
import com.cn.common.controller.BaseController;
import com.cn.common.utils.ResponseUtil;
import com.cn.system.domain.RoleDO;
import com.cn.system.service.RoleService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/sys/role")
@Controller
public class RoleController extends BaseController {
    String prefix = "system/role";
    @Autowired
    RoleService roleService;

    @RequiresPermissions("sys:role:role")
    @GetMapping()
    public String role() {
        return prefix + "/role";
    }

    @RequiresPermissions("sys:role:role")
    @GetMapping("/list")
    @ResponseBody()
    public List<RoleDO> list() {
        List<RoleDO> roles = roleService.list();
        return roles;
    }

    @RequiresPermissions(value = {"sys:role:add", "sys:role:edit"}, logical = Logical.OR)
    @RequestMapping("/modify")
    public String modify(String roleId, Model model) {
        RoleDO roleDO;
        if (null != roleId && !"".equals(roleId)) {
            roleDO = roleService.get(roleId);
        } else {
            roleDO = new RoleDO();
        }
        model.addAttribute("role", roleDO);
        return prefix + "/modify";
    }

    @Log("保存角色")
    @RequiresPermissions("sys:role:add")
    @PostMapping("/save")
    @ResponseBody
    ResponseUtil save(RoleDO role) {
        if (roleService.save(role) > 0) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.error(1, "保存失败");
        }
    }

    @Log("更新角色")
    @RequiresPermissions("sys:role:edit")
    @PostMapping("/update")
    @ResponseBody
    ResponseUtil update(RoleDO role) {
        if (roleService.update(role) > 0) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.error(1, "保存失败");
        }
    }

    @Log("删除角色")
    @RequiresPermissions("sys:role:remove")
    @PostMapping("/remove")
    @ResponseBody
    ResponseUtil save(String id) {
        if (roleService.remove(id) > 0) {
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.error(1, "删除失败");
        }
    }

    @RequiresPermissions("sys:role:batchRemove")
    @Log("批量删除角色")
    @PostMapping("/batchRemove")
    @ResponseBody
    ResponseUtil batchRemove(@RequestParam("ids[]") String[] ids) {
        int r = roleService.batchremove(ids);
        if (r > 0) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.error();
    }
}
